import React from 'react';
import { connect } from 'react-redux';
import { Input, Select, message } from 'antd';
import { generateUUID } from 'Utils/index';
import * as routerActions from 'react-router-redux';
import Api from 'Utils/api';
import moment from 'moment';
import './index.scss';

const Search = Input.Search;
const Option = Select.Option;
class Business extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      Treevalue: undefined,
      selectData: [],
      treeData: props.businessAreaData || [],
      selectTreeId: '',
      selectTypeName: '',
      searchValue: '',
      selectAlert: '',
      randomRecord: [],
      punishRecord: [],
      checkRecord: [], //巡查记录
    };
    this.renderRecord = ::this.renderRecord;
    this.initSearchData = ::this.initSearchData;
    this.initCheckRandom = ::this.initCheckRandom;
    this.renderRecordDetaile = ::this.renderRecordDetaile;
    this.initPunishRecord = ::this.initPunishRecord;
    this.renderpunishRecordDetaile = ::this.renderpunishRecordDetaile;
    this.initSearchData();
  }
  componentWillReceiveProps(nextProp) {
    this.setState({
      treeData: nextProp.businessAreaData,
      selectData: nextProp.selectData,
      // selectTreeId: this.state.selectTreeId ? this.state.selectTreeId : nextProp.businessAreaData[0].id
    }, () => {
      if (this.state.selectData.id) {
        this.initCheckRandom();
        this.initPunishRecord();
        this.initCheck();
      }
    });
  }
  initSearchData() {
    const { selectTreeId, selectTypeName, searchValue, selectAlert } = this.state;
    const query = {};
    query.offset = 0;
    query.limit = 10000;
    if (selectTreeId) { query.manage_gov_id = selectTreeId; }
    if (selectTypeName) { query.category = selectTypeName; }
    if (selectAlert) { query.level = selectAlert; }
    if (searchValue) { query.name_like = searchValue; }
    const api = new Api({
      method: 'GET',
      path: '/enterprises/type_gov_id',
      query,
      success: (res) => {
        this.props.reload(res.data_list, searchValue);
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  handleSearch(value) {
    this.setState({
      searchValue: value,
    }, () => {
      this.initSearchData();
    });
  }
  onChangeArea(Treevalue) {
    console.log(Treevalue);
    this.setState({
      selectTreeId: Treevalue ? parseInt(Treevalue, 10) : Treevalue,
    }, () => {
      this.initSearchData();
    });
  }
  //抽检记录
  initCheckRandom() {
    const api = new Api({
      method: 'GET',
      path: `/enterprise_details/product_check/${this.state.selectData.id}`,
      query: {
        offset: 0,
        limit: 2
      },
      success: (res) => {
        this.setState({
          randomRecord: res.data_list
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  //处罚记录
  initPunishRecord() {
    const api = new Api({
      method: 'GET',
      path: `/enterprise_details/justice_case/${this.state.selectData.id}`,
      query: {
        offset: 0,
        limit: 2
      },
      success: (res) => {
        this.setState({
          punishRecord: res.data_list
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  //巡查记录
  initCheck() {
    const api = new Api({
      method: 'GET',
      path: `/enterprise_details/yong_an_tong_check/${this.state.selectData.id}`,
      query: {
        offset: 0,
        limit: 2
      },
      success: (res) => {
        this.setState({
          checkRecord: res.data_list
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  getRes(id) {
    if (parseInt(id, 10) === 1) {
      return {
        color: '#F02828',
        label: '不合格'
      };
    } else if (parseInt(id, 10) === 0) {
      return {
        color: '#23FF76',
        label: '合格'
      };
    }
    return {
      color: '#F02828',
      label: '未检验'
    };
  }
  renderRecord() {
    const { checkRecord } = this.state;
    const nodeInfo = [];
    for (let i = 0, len = checkRecord.length; i < len; i++) {
      nodeInfo.push((
        <div className="record" key={generateUUID()}>
          <span>{checkRecord[i].upload_date ? moment(checkRecord[i].upload_date).format('YYYY/MM/DD') : ''}</span>
          <span className="result" />
        </div>
      ));
    }
    return nodeInfo;
  }
  renderRecordDetaile(data) {
    const nodeInfo = [];
    for (let i = 0, len = data.length; i < len; i++) {
      const res = this.getRes(data[i].check_result);
      nodeInfo.push((
        <div className="record" key={generateUUID()}>
          <span>{data[i].check_date ? moment(data[i].check_date).format('YYYY/MM/DD') : ''}</span>
          <span className="result" style={{ color: res.color }}>{res.label}</span>
        </div>
      ));
    }
    return nodeInfo;
  }
  renderpunishRecordDetaile(data) {
    console.log(data);
    const nodeInfo = [];
    for (let i = 0, len = data.length; i < len; i++) {
      nodeInfo.push((
        <div className="record" key={generateUUID()}>
          <span>{data[i].case_date ? moment(data[i].case_date).format('YYYY/MM/DD') : ''}</span>
          <span className="result">{data[i].status}</span>
        </div>
      ));
    }
    return nodeInfo;
  }
  handleTypeChange(value) {
    this.setState({
      selectTypeName: value
    }, () => {
      this.initSearchData();
    });
  }
  handleAlertChange(value) {
    this.setState({
      selectAlert: value
    }, () => {
      this.initSearchData();
    });
  }
  onSelect(value, e) {
    this.props.mapCenter(e.props.item);
  }
  render() {
    const { treeData, randomRecord, punishRecord, checkRecord, selectTreeId, selectTypeName, selectAlert } = this.state;
    const { selectData } = this.props;
    return (
      <div className="business">
        <div className="business-padding">
          <div className="search">
            <Search
              placeholder="查询"
              style={{ width: 360 }}
              onSearch={this.handleSearch.bind(this)}
            />
          </div>
          <div className="select">
            <Select style={{ width: 360 }} placeholder="预警类型" value={selectAlert} onChange={this.handleAlertChange.bind(this)}>
              <Option value="">全部</Option>
              <Option value="3">告警</Option>
              <Option value="2">警示</Option>
              <Option value="1">预警</Option>
              <Option value="4">正常</Option>
            </Select>
          </div>
          <div className="select">
            <Select style={{ width: 360 }} placeholder="主体类别" value={selectTypeName} onChange={this.handleTypeChange.bind(this)}>
              <Option value="">所有</Option>
              <Option value="食品流通">食品流通</Option>
              <Option value="餐饮服务">餐饮服务</Option>
              <Option value="食品生产">食品生产</Option>
              <Option value="药品经营">药品经营</Option>
              <Option value="保健食品">保健食品</Option>
              <Option value="化妆品">化妆品</Option>
              <Option value="医疗器械">医疗器械</Option>
            </Select>
          </div>
          <div className="select">
            <Select style={{ width: 360 }} value={selectTreeId && selectTreeId.toString()} placeholder="区域" onChange={this.onChangeArea.bind(this)} onSelect={this.onSelect.bind(this)}>
              <Option value="" key={''}>全部</Option>
              {
                treeData && treeData.length > 0 ? treeData.map(item => (
                  <Option value={item.id.toString()} key={item.id} item={item}>{item.name}</Option>
                )) : ''
              }
            </Select>
          </div>
        </div>
        <div className="record-wrap">
          <div onClick={() => { this.props.dispatch(routerActions.push(`/system/bigdata/map/records/${selectData.id}`)); }} className="title">
            巡查记录 <div className="title-more">{checkRecord.length > 0 ? '更多》' : ''}</div>
          </div>
          <div className="content">
            {
              checkRecord.length > 0 ? this.renderRecord() : ''
            }
          </div>
          <div onClick={() => { this.props.dispatch(routerActions.push(`/system/bigdata/map/records/check_record/${selectData.id}`)); }} className="title">
            抽检记录 <div className="title-more">{randomRecord.length > 0 ? '更多》' : ''}</div>
          </div>
          <div className="content">
            {
              randomRecord.length > 0 ? this.renderRecordDetaile(randomRecord) : ''
            }
          </div>
          <div onClick={() => { this.props.dispatch(routerActions.push(`/system/bigdata/map/records/punishment_record/${selectData.id}`)); }} className="title">
            行政处罚记录 <div className="title-more">{punishRecord.length > 0 ? '更多》' : ''}</div>
          </div>
          <div className="content">
            {
              punishRecord.length > 0 ? this.renderpunishRecordDetaile(punishRecord) : ''
            }
          </div>
          {
            <div className="info">
              <div className="item">企业名称：{selectData ? selectData.name : ''}</div>
              <div className="item">地址：{selectData ? selectData.address : ''}</div>
              <div className="item">法人：{selectData ? selectData.legal_entity : ''}</div>
            </div>
          }
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}

export default connect(mapStateToProps)(Business);
